
<!--suppress ALL -->
<template>
  <div class="app-container">
    <el-form label-width="120px">
      <el-form-item label="视频名称">
        <el-input v-model="video.title" placeholder="视频名称(随便填写)"/>
      </el-form-item>

      <el-form-item label="视频热度">
        <el-input-number v-model="video.sort" :min="0" :max="10000" controls-position="right" style="width: 130px"/>
      </el-form-item>

      <el-form-item label="视频状态">
        <el-select v-model="video.state" placeholder="请选择" style="width: 96px">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="视频封面" style="margin-top: 20px">

        <template slot-scope="scope">
          <el-upload
            class="avatar-uploader"
            :action="BASE_API+'/itservice/imageadmin'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img :alt="video.title" v-if="video.videoCover" :src="video.videoCover" class="avatar" style="width: 500px; height: 300px" title="点击更换">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </template>

        <image-cropper
          v-show="imagecropperShow"
          :width="300"
          :height="300"
          :key="imagecropperKey"
          :url="BASE_API+'/itservice/imageadmin'"
          field="file"
          @close="close"
          @crop-upload-success="cropSuccess"/>

      </el-form-item>

      <el-form-item label="视频">
        <div v-if="video.videoUrl">
          <el-label >{{ video.videoOriginalName }}<i class="el-icon-view el-icon--right"/>  </el-label>
          <el-button v-if="video.videoUrl" type="success" size="mini" plain @click="openVideoDisplay(video.videoUrl)">查看</el-button>
        </div>
        <div v-else>
          <el-label style="color: red;">暂无视频,请先上传<i class="el-icon-view el-icon--right"/>  </el-label>
        </div>
      </el-form-item>

      <el-form-item label="上传视频">
        <template>
          <div class="container">
            <div id="upload_video" class="upload_video">
              <el-upload
                ref="upload"
                :http-request="uploadVideo"
                :limit="1"
                :on-exceed="handleExceed"
                :on-remove="handleRemove"
                :on-change="handleChange"
                :before-remove="beforeRemove"
                :auto-upload="false"
                class="upload-demo"
                action="#">
                <el-button slot="trigger" size="small" type="primary">选取视频</el-button>
                <el-button style="margin-left: 40px;" size="small" type="success" @click="submitUpload">点击上传</el-button>
                <el-progress
                  :text-inside="true"
                  :stroke-width="18"
                  :percentage="progress"
                  class="progress"
                  status="success"/>
                <div slot="tip" class="el-upload__tip">建议上传mp4文件, 且不超过500M</div>
              </el-upload>
            </div>
          </div>
        </template>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="addOrEidtVideo">{{ addOrEidtArticleTitle }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import videoApi from '@/api/video'
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
import TcVod from 'vod-js-sdk-v6'
import { getSignature } from '@/api/video'
import axios from 'axios'
import VueAxios from 'vue-axios'
VueAxios.prototype.$http = axios
export default {
  components: { ImageCropper, PanThumb },
  data() {
    return {
      oldVideoSourceId: '',
      videoId: '',
      video: {
        title: '',
        videoUrl: '',
        videoSourceId: '',
        videoCover: 'https://lk-1303842271.cos.ap-beijing.myqcloud.com/guli-edu%2Favatar%2F2022%2F07%2F04%2Fb48ee5add9fe4aa99b1e04f02f721efa.jpg',
        sort: 0,
        state: 0
      },
      saveBtnDisabled: false, // 保存按钮是否禁用,
      imagecropperShow: false, // 默认上传的组件是否显示
      imagecropperKey: 0, // 上传组件key值
      BASE_API: process.env.BASE_API,// 获取dev.env.js端口号

      fileList: [], // 文件列表
      file: '', // 上传的文件
      videoURL: '', // 上传成功后的地址
      progress: 0, // 进度条百分比
      fileId: '', // 上传视频获取成功后拿到的fileID【备用】
      msg: '', // 云点播签名
      verifyContent: '', // 验证内容

      //状态选择下拉框
      options: [{
        value: 0,
        label: '未发布'
      }, {
        value: 1,
        label: '已发布'
      }],

      // 提交文字
      addOrEidtArticleTitle: "添加"
    }
  },

  mounted() {
    const that = this
    // 获取签名 这里的签名请求是由后端提供的，只需要拿到后端给的签名请求即可
    videoApi.getSign()
      .then((res) => {
        // console.log("==========获取签名=========")
        // console.log(res)
        that.msg = res.data.signature
      })
  },

  created: function () {
    if (this.$route.params && this.$route.params.id) {
      this.addOrEidtArticleTitle = "修改"
      this.videoId = this.$route.params.id
      console.log("============路由id=============")
      console.log(this.$route.params.id)
      // 调用根据id查询方法
      this.getVideoInfoById()
    }
  },

  watch: {
    $route(to, from) {
      this.video={
        title: '',
        videoUrl: '',
        videoSourceId: '',
        videoCover:'https://lk-1303842271.cos.ap-beijing.myqcloud.com/guli-edu%2Favatar%2F2022%2F07%2F04%2Fb48ee5add9fe4aa99b1e04f02f721efa.jpg',
        sort: 0,
        state: 0
      }
    }
  },

  methods: {

    //上传页播放视频
    openVideoDisplay(videoUrl) {
      this.$confirm('将重新打开新标签页播放此视频, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.open(videoUrl, '_blank')
      })
    },

    //根据id获取视频信息
    getVideoInfoById() {
      videoApi.getVideoInfoById(this.videoId)
        .then(response => {

          console.log("===========根据id获取视频===========")
          console.log(response.data)
          this.video = response.data.video
        })
    },

    // 添加和修改视频的方法
    addOrEidtVideo() {
      if (this.video.title===''){
        this.$message({
          message: "视频名不能为空",
          type: "warning"
        })
        return
      }
      //修改视频
      if (this.videoId!=="") {
        this.$confirm('确定修改视频?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.video.videoCover === 'https://lk-1303842271.cos.ap-beijing.myqcloud.com/guli-edu%2Favatar%2F2022%2F07%2F04%2Fb48ee5add9fe4aa99b1e04f02f721efa.jpg') {
            this.$notify({
              message: '使用了默认封面作为视频封面',
              type: 'warning'
            })
          }
          videoApi.updateVideo(this.video)
            .then(response => { // 修改成功
              // 提示信息
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
              // 回到列表页面 路由跳转
              this.$router.push({path: '/video/list'})
            })
        })
      } else {
        this.$confirm('确定添加视频?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //添加视频
          videoApi.addVideo(this.video)
            .then(response => { // 添加成功
              // 提示信息
              this.$message({
                type: 'success',
                message: '添加成功!'
              })
              // 回到列表页面 路由跳转
              this.$router.push({path: '/video/list'})
            })
        })
      }
    },

    handleAvatarSuccess(res, file)
    {
      console.log("============上传文件=============")
      console.log("res = ", res)
      console.log("file = ", file)
      console.log("res = ", res.data.url)

      this.video.videoCover = res.data.url
    },

    beforeAvatarUpload(file)
    {
      const isFormat = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isFormat) {
        this.$message.error('上传头像图片只能是 jpg/jpeg/png 格式!');
      }
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isFormat && isLt10M;
    },

    // 关闭上传弹窗
    close()
    {
      this.imagecropperShow = false
      // 解决上传完图片重新上传需要点两次，将id+1
      this.imagecropperKey += 1
    },

    // 上传成功方法
    cropSuccess(data)
    {
      // 关闭弹窗
      this.imagecropperShow = false
      // 上传之后接口返回图片地址
      this.video.videoCover = data.url
      // 解决上传完图片重新上传需要点两次，将id+1
      this.imagecropperKey += 1
    },


    // 待上传列表
    handleChange(file, fileList) {
      this.file = file
      this.fileList = fileList
      // console.log("=======待上传列表=======")
      // console.log(file)
      // console.log(fileList)
      // console.log(fileList.length)
    },

    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },

    // 点击上传视频时
    submitUpload() {
      this.$confirm('确定上传视频?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.fileList.length < 1) return this.$alert('请先选取视频，再进行上传', '提示')
        this.uploadVideo()
      })

    },
    // 自定义上传
    uploadVideo(e) {
      const that = this
      // console.log(this.fileList[0].raw)
      if (this.fileList.length < 1) {
        window.alert('您还没有选取文件')
      } else {
        // 必须以函数的形式返回 sdk参数限制
        const getSignature = async() => {
          const data = that.msg
          // console.log(this.msg)
          return data
        }
        // console.log(this.msg)
        const tcVod = new TcVod({
          getSignature: getSignature // 获取上传签名的函数
        })
        // 获取通过elementui上传到本地的文件 因为参数类型必须为file 不能直接以对象的形式传输
        const mediaFile = this.fileList[0].raw
        const uploader = tcVod.upload({
          mediaFile: mediaFile
        })
        // 监听上传进度
        uploader.on('media_progress', info => {
          this.progress = parseInt(info.percent * 100)
        })
        // 上传结束时，将url存到本地
        uploader.done().then(doneResult => {
          this.fileId = doneResult.fileId
          this.videoURL = doneResult.video.url
          this.verifyContent = doneResult.video.verify_content

          console.log("=======上传视频返回结果=======")
          console.log(doneResult)
          console.log(this.fileId)
          console.log(this.videoURL)
          console.log(this.verifyContent)

          // 上传成功，将video对象参数填充
          // console.log(this.file.name)
          this.oldVideoSourceId = this.video.videoSourceId
          //清除旧视频
          if (this.oldVideoSourceId!==''){
            console.log("=======删除旧视频=======")
            console.log(this.video)
            console.log(this.oldVideoSourceId)
            videoApi.removeTencentVideo(this.oldVideoSourceId)
              .then(response => {
                this.$notify({
                  message: "清除旧视频成功",
                  type: "success"
                })
              })
          }
          this.video.videoSourceId = this.fileId
          this.video.videoOriginalName = this.file.name
          this.video.videoUrl = this.videoURL
        })
      }
    },

    // 点击删除上传视频列表
    handleRemove(file, fileList) {
      // console.log("=======删除列表=======")
      // console.log(file)
      // console.log(fileList)
      // console.log(fileList.length)
      // 清空表单
      this.file = ''
      this.fileList = []
      this.video.videoSourceId = ''
      this.video.videoOriginalName = ''
      this.video.videoUrl = ''
    },

    // 移除文件提示
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}? `)
    }
  }
}

</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
